/*
 *  Copyright (C) 2003 MediaRush, Inc.
 *
 *  This software is copyrighted to MediaRush, Inc. It cannot
 *  be distributed or modified without the express written 
 *  approval of MediaRush, Inc.
 * 
 *  postmaster@mediarush.com
 * 
 *  File: GC100ReadThread.java
 *
 */

package com.cidero.bridge.gc100;

import java.io.*;
import java.net.*;

import com.cidero.util.SynchronizedQueue;

/**
 * Describe class <code>GC100ReadThread</code> here.
 *
 * Thread that sits and reads data from the GlobalCache GC100 command socket.
 *
 * Implementing the reader as a separate thread allows for detection of
 * command timeouts while still using a blocking read 
 *
 * @author <a href="mailto:newell@mediarush.com"></a>
 * @version 1.0
 */
public class GC100ReadThread implements Runnable
{
  Socket socket = null;
  SynchronizedQueue queue;
  long timeStampCount = 0;

  public GC100ReadThread( Socket socket, SynchronizedQueue queue )
  {
    this.socket = socket;
    this.queue = queue;
  }
  
  private Thread readerThread = null;  // for clean shutdown via stop()
  
  public void run()
  {
    System.out.println("GC100ReadThread: Running...");

    Thread thisThread = Thread.currentThread();
    
    BufferedReader reader;

    try 
    {
      reader = new BufferedReader( 
                    new InputStreamReader( socket.getInputStream() ) );
    }
    catch( Exception e )
    {
      System.out.println( e );
      return;
    }

    while( readerThread == thisThread )
    {
      //
      // Read lines one at a time, passing messages back to main thread
      // On error terminate read thread
      //
      try 
      {
        String responseLine = reader.readLine();
        
        //
        // If this is a response to a command, forward it to the
        // command thread. Asynchronous notifications (codes 900-999)
        // are handled separately
        //
        System.out.println("GC100ReadThread: Response: " + responseLine );

        if( ! queue.add( responseLine, 2000 ) )
          System.out.println("GC100ReadThread: dropping response");
      }
      catch( Exception e )
      {
        System.out.println("GC100ReadThread: Error: " + e );
        return;
      }
      
    }
    
    System.out.println("GC100ReadThread: Shutting down...");

  }

  public void start()
  {
    readerThread = new Thread( this );
    readerThread.start();
  }
  
  public void stop()
  {
    readerThread = null;
  }
  
}
